package com.futao.spring.lifecycle.cycle.scope;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.stereotype.Component;

/**
 * 自定义Bean的Scope
 * target: 每个线程获取到的Bean实例都是同一个
 *
 * @author ft
 * @date 2021/1/28
 */
@Component(ThreadScope.SCOPE)
public class ThreadScope implements Scope, BeanFactoryPostProcessor {
    /**
     * 线程本地变量持有当前线程获取到的Bean实例
     */
    private static final ThreadLocal<Object> THREAD_LOCAL_BEAN = new ThreadLocal<>();
    /**
     * 自定义的Scope的名称
     */
    public static final String SCOPE = "threadLocal";

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Object o = THREAD_LOCAL_BEAN.get();
        if (o == null) {
            THREAD_LOCAL_BEAN.set(objectFactory.getObject());
        }
        return THREAD_LOCAL_BEAN.get();
    }

    @Override
    public Object remove(String name) {
        Object o = THREAD_LOCAL_BEAN.get();
        THREAD_LOCAL_BEAN.remove();
        return o;
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {

    }

    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // 将自定义的Scope注册到容器中
        beanFactory.registerScope(ThreadScope.SCOPE, this);
    }
}
